package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class orderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 */5 * * * ?")//每隔五分钟执行一次
    public void orderTime(){
        log.info("订单超时未支付处理");

        //获取到所有未支付订单
        List<Orders> ordersList = orderMapper.getTimeOrder(Orders.PENDING_PAYMENT);

        for (Orders orders : ordersList) {
            LocalDateTime time = orders.getOrderTime().plusMinutes(1);
            if (LocalDateTime.now().isAfter(time)) {
                // 当前时间在订单时间加1分钟之后，说明订单超过了1分钟未支付，需要取消订单
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时未支付，自动取消");
                orderMapper.updateOrders(orders);
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")//每天1点执行 处理前天订单
    public void finish(){

        log.info("订单派送中集中处理");

        //获取所有正在派送中的订单
        List<Orders> ordersList = orderMapper.getTimeOrder(Orders.DELIVERY_IN_PROGRESS);
        for (Orders orders : ordersList) {
            LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
            if (orders.getOrderTime().isBefore(time)){
                orders.setStatus(Orders.COMPLETED);
                orderMapper.updateOrders(orders);
            }
        }

    }
}
